package com.main.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.stereotype.Repository;

import com.main.bean.User;

@Repository("userDao")
public class UserDao {

	@Autowired
	private DataSource dataSource;
	
	@Autowired
	private JdbcTemplate jdbcTemplate;
	
	/**
	 * 查询用户
	 * @param user
	 * @return
	 */
	public User getUserByName(final User user){
		String sql="select * from ws_user where user_name=?";
		
	   jdbcTemplate.query(sql, new Object[]{user.getUser_name()},new RowCallbackHandler(){
			public void processRow(ResultSet rs) throws SQLException {
				                              user.setCreate_time(new Date(rs.getDate("create_time").getTime()));
				                              user.setEmail(rs.getString("email"));
				                              user.setUser_name(rs.getString("user_name"));
				                              user.setPassword(rs.getString("password"));
				                              user.setState(rs.getString("state"));
				                              user.setLogin_time(new Date(rs.getDate("login_time").getTime()));
				                        }          
		});  
		
		return user;
	}
	
	/**
	 * 查询用户
	 * @param user
	 * @return
	 */
	public User getUserByEmail(final User user){
		String sql="select * from ws_user where email=?";
		
	   jdbcTemplate.query(sql, new Object[]{user.getEmail()},new RowCallbackHandler(){
			public void processRow(ResultSet rs) throws SQLException {
				                              user.setCreate_time(new Date(rs.getDate("create_time").getTime()));
				                              user.setEmail(rs.getString("email"));
				                              user.setUser_name(rs.getString("user_name"));
				                              user.setPassword(rs.getString("password"));
				                              user.setState(rs.getString("state"));
				                              user.setLogin_time(new Date(rs.getDate("login_time").getTime()));
				                        }          
		});  
		
		return user;
	}
	
	/**
	 * 查询是否存在用户
	 * @param user
	 * @return
	 */
	public int getUserCount(User user){
		String sql="select count(*) from ws_user where email=? or user_name=?";
		Integer result=jdbcTemplate.queryForObject(sql,new Object[]{user.getEmail(),user.getUser_name()},Integer.class);
		return result.intValue();
	}
	
	/**
	 * 添加用户
	 */
	public int add(User user){
		String sql="insert into ws_user(id,user_name,email,password,create_time,login_time) values(ws_user_seq.nextval,?,?,?,?,sysdate)";
		return jdbcTemplate.update(sql, new Object[]{user.getUser_name(),user.getEmail(),user.getPassword(),user.getCreate_time()});
	}
	
}
